package com.example.patchouli_knowledge

import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.IBinder
import android.os.Vibrator
import android.view.GestureDetector
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.view.WindowManager
import android.os.Handler
import android.os.Looper
import android.util.Log
import io.flutter.plugin.common.MethodChannel

/**
 * 长按检测服务，在屏幕上覆盖一个透明的View，用于检测长按事件
 */
class LongPressDetectionService : Service() {
    private lateinit var windowManager: WindowManager
    private lateinit var overlayView: View
    private lateinit var gestureDetector: GestureDetector
    private lateinit var methodChannel: MethodChannel
    private lateinit var vibrator: Vibrator
    private val handler = Handler(Looper.getMainLooper())
    private var isDetecting = false

    companion object {
        private const val TAG = "LongPressDetection"
        private const val LONG_PRESS_DURATION = 800L // 长按时间阈值，单位毫秒
    }

    override fun onCreate() {
        super.onCreate()
        Log.d(TAG, "长按检测服务创建")
        
        windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
        vibrator = getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
        
        // 创建透明覆盖层
        setupOverlayView()
        
        // 初始化手势检测器
        setupGestureDetector()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        Log.d(TAG, "长按检测服务启动")
        
        // 如果已经在检测中，不重复启动
        if (!isDetecting) {
            addOverlayToWindow()
            isDetecting = true
        }
        
        // 服务被杀死后自动重启
        return START_STICKY
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onDestroy() {
        Log.d(TAG, "长按检测服务销毁")
        
        try {
            if (isDetecting) {
                removeOverlayFromWindow()
                isDetecting = false
            }
        } catch (e: Exception) {
            Log.e(TAG, "清理服务资源时出错: ${e.message}")
        }
        
        super.onDestroy()
    }

    /**
     * 设置覆盖层View
     */
    private fun setupOverlayView() {
        overlayView = View(this)
        overlayView.setBackgroundColor(android.graphics.Color.TRANSPARENT)
        
        // 设置触摸监听器
        overlayView.setOnTouchListener { _, event ->
            try {
                // 只处理手势检测，不拦截事件
                val handled = gestureDetector.onTouchEvent(event)
                
                // 始终返回false，让触摸事件继续传递给下层应用
                // 这样既能检测长按，又不会拦截用户的正常操作
                false
            } catch (e: Exception) {
                Log.e(TAG, "处理触摸事件时出错: ${e.message}")
                false
            }
        }
    }

    /**
     * 设置手势检测器
     */
    private fun setupGestureDetector() {
        gestureDetector = GestureDetector(this, object : GestureDetector.SimpleOnGestureListener() {
            override fun onLongPress(e: MotionEvent) {
                Log.d(TAG, "检测到长按事件: x=${e.x}, y=${e.y}")
                
                // 触发轻微振动反馈
                vibrator.vibrate(100)
                
                // 通知Flutter端
                notifyFlutterOfLongPress()
            }
        })
    }

    /**
     * 将覆盖层添加到窗口
     */
    private fun addOverlayToWindow() {
        val params = WindowManager.LayoutParams(
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
            // 使用安全的标志组合，确保不会拦截用户操作
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
                    WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL or
                    WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
            android.graphics.PixelFormat.TRANSLUCENT
        )
        params.gravity = Gravity.TOP or Gravity.START
        
        try {
            // 在添加覆盖层前检查是否已经添加
            if (!isDetecting) {
                windowManager.addView(overlayView, params)
                Log.d(TAG, "覆盖层已添加到窗口，使用安全触摸设置")
            }
        } catch (e: Exception) {
            Log.e(TAG, "添加覆盖层失败: ${e.message}")
        }
    }

    /**
     * 从窗口移除覆盖层
     */
    private fun removeOverlayFromWindow() {
        try {
            if (::overlayView.isInitialized && isDetecting) {
                windowManager.removeView(overlayView)
                Log.d(TAG, "覆盖层已从窗口移除")
            }
        } catch (e: Exception) {
            Log.e(TAG, "移除覆盖层失败: ${e.message}")
        }
    }

    /**
     * 通知Flutter端长按事件
     */
    private fun notifyFlutterOfLongPress() {
        // 在主线程中执行，确保安全
        handler.post {
            try {
                // 通过方法通道通知Flutter
                MainActivity.longPressChannel?.invokeMethod("onLongPress", null)
                Log.d(TAG, "通知Flutter端长按事件")
            } catch (e: Exception) {
                Log.e(TAG, "通知Flutter端长按事件失败: ${e.message}")
            }
        }
    }
} 